package com.snapan.service.impl;

import com.snapan.common.PageResult;
import com.snapan.dao.ShareDao;
import com.snapan.entity.ShareFile;
import com.snapan.entity.UserFile;
import com.snapan.es.entity.FileShareDocument;
import com.snapan.es.entity.UserFileDocument;
import com.snapan.es.repository.FileShareDocumentRepository;
import com.snapan.service.ShareService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 分享服务实现类
 */
@Service
@Transactional
public class ShareServiceImpl implements ShareService {

    @Autowired
    private ShareDao shareDao;

    @Autowired
    private FileShareDocumentRepository esRepository;

    @Override
    public PageResult<ShareFile> getShareList(int pageSize, int pageNo, int userId) {
        try {
            // 计算偏移量
            int offset = (pageNo - 1) * pageSize;
            
            // 获取总数
            int total = shareDao.countByUserId(userId);
            
            // 获取列表
            List<ShareFile> list = shareDao.getShareList(userId, offset, pageSize);
            
            // 计算总页数
            int totalPages = (total + pageSize - 1) / pageSize;
            
            PageResult<ShareFile> pageResult = new PageResult<>();
            pageResult.setList(list);
            pageResult.setTotal((long) total);
            pageResult.setPageNum(pageNo);
            pageResult.setPages(totalPages);
            
            return pageResult;
        } catch (Exception e) {
            throw new RuntimeException("获取分享列表失败", e);
        }
    }

    @Override
    public ShareFile getShareByToken(String token) {
        try {
            return shareDao.getByToken(token);
        } catch (Exception e) {
            throw new RuntimeException("获取分享信息失败", e);
        }
    }

    @Override
    public ShareFile createShare(ShareFile shareFile, boolean enablePassword) {
        try {
            // 生成唯一分享码
            String shareCode = generateShareCode();
            shareFile.setShareCode(shareCode);
            
            // 如果启用了密码，生成4位随机数字密码
            if (enablePassword) {
                String randomPassword = generateRandomPassword();
                shareFile.setPassword(randomPassword);
                System.out.println("生成的分享密码: " + randomPassword);
            } else {
                shareFile.setPassword(null);
            }
            
            // 设置默认值
            if (shareFile.getStatus() == null) {
                shareFile.setStatus((byte) 1); // 默认启用
            }
            
            Date now = new Date();
            shareFile.setCreateTime(now);
            
            // 插入数据库
            shareDao.insert(shareFile);
            
            return shareFile;
        } catch (Exception e) {
            throw new RuntimeException("创建分享失败", e);
        }
    }
    
    @Override
    public ShareFile verifyPassword(String shareCode, String password) {
        try {
            // 获取分享信息
            ShareFile shareFile = shareDao.getByToken(shareCode);
            
            if (shareFile == null) {
                return null;
            }
            
            // 检查分享状态
            if (shareFile.getStatus() != 1) {
                return null; // 分享已被禁用
            }
            
            // 检查是否过期
            if (shareFile.getExpireTime() != null && 
                shareFile.getExpireTime().before(new Date())) {
                return null; // 分享已过期
            }
            
            // 验证密码（如果设置了密码）
            if (shareFile.getPassword() != null && !shareFile.getPassword().isEmpty()) {
                if (!shareFile.getPassword().equals(password)) {
                    return null; // 密码错误
                }
            }
            
            return shareFile;
        } catch (Exception e) {
            throw new RuntimeException("验证密码失败", e);
        }
    }
    
    /**
     * 生成4位随机数字密码
     */
    private String generateRandomPassword() {
        int randomNum = (int)(Math.random() * 9000) + 1000; // 1000-9999
        return String.valueOf(randomNum);
    }

    @Override
    public boolean updateShare(ShareFile shareFile) {
        try {
            shareFile.setUpdateTime(new Date());
            int result = shareDao.update(shareFile);
            return result > 0;
        } catch (Exception e) {
            throw new RuntimeException("更新分享失败", e);
        }
    }

    @Override
    public boolean deleteShare(Long id) {
        try {
            int result = shareDao.delete(id);
            return result > 0;
        } catch (Exception e) {
            throw new RuntimeException("删除分享失败", e);
        }
    }

    @Override
    public boolean recordAccess(String token) {
        try {
            // 更新访问次数和最后访问时间
            return shareDao.recordAccess(token) > 0;
        } catch (Exception e) {
            throw new RuntimeException("记录访问失败", e);
        }
    }

    /**
     * 生成分享码
     */
    private String generateShareCode() {
        // 使用UUID生成唯一标识，去掉横线并截取前16位
        return UUID.randomUUID().toString().replace("-", "").substring(0, 16);
    }

    public void syncAllValidShareFileToEs() {
        // 1. 查询所有有效用户文件,没被彻底删除的文件，在回收站里的不算
        List<ShareFile> shareFileList = shareDao.selectAllValid();
        for (ShareFile shareFile : shareFileList) {
            // 3. 构建 ES 实体并同步
            FileShareDocument esDoc = buildEsDocument(shareFile);
            esRepository.save(esDoc);
            System.out.println("同步 ES 完成：userFileId=" + shareFile.getId() + "，fileName=" + shareFile.getFileName());
        }
        System.out.println("所有有效用户文件同步 ES 结束，共 " + shareFileList.size() + " 条");
    }

    public void syncShareFileToEs(Long shareFileId) {
        // 1. 查询用户文件
        ShareFile shareFile = shareDao.getById(shareFileId);
        System.out.println(shareFile);
        if (shareFile == null) {
            throw new RuntimeException("用户文件不存在或已失效");
        }
        //目录不会同步到Es
        if(shareFile.getIsDirectory()==0&& shareFile.getStatus()==1){
            // 3. 构建 ES 实体并同步
            FileShareDocument esDoc = buildEsDocument(shareFile);
            esRepository.save(esDoc);
        }

   }

    /**
     * 工具方法：构建 ES 实体
     */
    private FileShareDocument buildEsDocument(ShareFile shareFile) {
        FileShareDocument esDoc = new FileShareDocument();
        esDoc.setId(shareFile.getId());
        esDoc.setUserId(shareFile.getUserId());
        esDoc.setFileId(shareFile.getFileId());
        esDoc.setFileName(shareFile.getFileName());
        esDoc.setShareCode(shareFile.getShareCode());
        esDoc.setPassword(shareFile.getPassword());
        esDoc.setCreateTime(shareFile.getCreateTime());
        esDoc.setStatus(shareFile.getStatus());
        esDoc.setExpireTime(shareFile.getExpireTime());
        esDoc.setFileSize(shareFile.getFileSize());
        esDoc.setFileSuffix(shareFile.getSuffix());
        return esDoc;
    }

}
